package org.soulraven.games.memory.ui.game.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.SwingUtilities;

import org.apache.log4j.Logger;
import org.soulraven.games.memory.ui.game.DisplayableCard;

public class SecondSelectionResolver implements ActionListener {

	private static final Logger LOGGER = Logger.getLogger(SecondSelectionResolver.class);

	private SelectionController controller = null;

	SecondSelectionResolver(final SelectionController controller) {
		this.controller = controller;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		LOGGER.debug("Second selection");
		final DisplayableCard card = (DisplayableCard) e.getSource();
		if (card.isSelectable()) {
			LOGGER.debug("Setting card number " + card.getNumber() + " as not selectable and visible");
			card.setSelectable(Boolean.FALSE);
			card.setHidden(Boolean.FALSE);
			controller.disableAllCards();

			processEvent(card);
			controller.selectionFinished();
		}
	}

	private void processEvent(final DisplayableCard secondSelection) {
		final DisplayableCard firstSelection = controller.getPreviousSelection();
		final boolean match = firstSelection.getNumber() == secondSelection.getNumber();
		controller.pairShown(match);
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					LOGGER.debug("Waiting 2 seconds");
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					LOGGER.error("Can't wait 2 seconds", e);
				}
				if (match) {
					matchesFound(firstSelection, secondSelection);
				}
				else {
					matchesNotFound(firstSelection, secondSelection);
				}
				controller.enableAllSelectableCards();
				controller.setPreviousSelection(null);
			}
		});
	}

	private void matchesNotFound(final DisplayableCard firstSelection,
			final DisplayableCard secondSelection) {
		LOGGER.debug("Resetting Action Listener selections");
		LOGGER.debug("Setting card number " + firstSelection.getNumber() + " as selectable and not visible");
		firstSelection.setHidden(Boolean.TRUE);
		firstSelection.setSelectable(Boolean.TRUE);
		LOGGER.debug("Setting card number " + secondSelection.getNumber() + " as selectable and not visible");
		secondSelection.setHidden(Boolean.TRUE);
		secondSelection.setSelectable(Boolean.TRUE);
		controller.matchesNotFound();
	}

	private void matchesFound(final DisplayableCard firstSelection,
			final DisplayableCard secondSelection) {
		LOGGER.debug("Disabling card number " + firstSelection.getNumber());
		firstSelection.setEnabled(Boolean.FALSE);
		LOGGER.debug("Disabling card number " + secondSelection.getNumber());
		secondSelection.setEnabled(Boolean.FALSE);
		controller.matchesFound();
	}
}
